# -*- coding: utf-8 -*-
# 导入必要的库
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import metrics
from sklearn.metrics import mean_absolute_error
from sklearn.metrics import mean_squared_error
import pickle
from config.dataset import dataset
from config.logger import *


def mape(actual, pred):
    actual, pred = np.array(actual), np.array(pred)
    return np.mean(np.abs((actual - pred) / actual)) * 100


def test():
    load_model = pickle.load(open(args.load_model_path, "rb"))
    print(args.load_model_path)
    print(load_model)
    logger = logger1()
    _, test_data, _, _, y_test, df2 = dataset(logger)
    y_predict = load_model.predict(test_data)
    y_pre = np.array(y_predict)  # 列表转数组
    y_pre = y_pre.reshape(args.cut, 1)
    y_pre = y_pre[:, 0]

    # 计算指标
    print("\n""**********2021年数据集测试指标**********")
    # 输出精度指标
    # print("MAE = ", mean_absolute_error(y_pre, y_test))
    # print("MSE = ", mean_squared_error(y_pre, y_test))

    close_max = df2['target_col'].max()
    close_min = df2['target_col'].min()

    data_true = pd.DataFrame(y_test)  # 归一化的真实数据
    true_nums = []
    preds_nums = []

    for i in range(len(data_true)):
        # print(y_test[i])
        true_num = y_test[i][0] * (close_max - close_min) + close_min
        preds_num = y_pre[i] * (close_max - close_min) + close_min

        true_nums.append(true_num)
        preds_nums.append(preds_num)
    print("MAPE = ", mape(true_nums, preds_nums))
    print("R2 = ", metrics.r2_score(true_nums, preds_nums))  # R2
    print("MAE = ", mean_absolute_error(true_nums, preds_nums))
    print("MSE = ", mean_squared_error(true_nums, preds_nums))

    # 画图
    x_axis = range(len(preds_nums))
    my_x_ticks = np.arange(0, len(preds_nums), 30)
    plt.xticks(my_x_ticks)
    plt.plot(x_axis, preds_nums)
    plt.plot(x_axis, true_nums)
    plt.title("Test Data")  # 添加标题
    plt.legend(('real', 'predict'))
    plt.xlabel('Time/day')
    plt.ylabel('Gas Consumption')
    plt.savefig(args.save_result_path)
    plt.show()
    return


if __name__ == '__main__':
    test()
